package com.globalwave.datasync.sqlgen;

import com.globalwave.common.db.SqlUtils;
import com.globalwave.datasync.SyncColumn;
import com.globalwave.datasync.SyncConfig;
import com.globalwave.datasync.SyncTable;

public class BaseBatchSqlGenerator extends BaseSqlGenerator {

	
	public BaseBatchSqlGenerator(SyncConfig config) {
		super(config);
	}

	@Override
	public void buildSourceQuerySQL(){

		StringBuffer sqlBuffer = new StringBuffer() ;

		SyncTable table = config.getSource() ;
		
		SyncColumn[] keys = table.getKeys();
		
		sqlBuffer.append(getSelectPart(table)) ;

        if (keys != null) {
			String flagFilter = keys[0].getRefColumnsCode() ;
			if (flagFilter != null) {
				flagFilter =" and " + flagFilter + "='R'" ;
			} else {
				flagFilter = "" ;
			}
			sqlBuffer.append(" where ").append(keys[0].getSyncColumnsCode()).append(">=? ")
			         .append(flagFilter).append(getFilter(table))
		             .append(" order by ").append(keys[0].getSyncColumnsCode()) ;

        }
        
    	int fetchSize = table.getConfig().getFetchSize() ;
    	if (fetchSize > 2000) {// 禁止大于2000
    		fetchSize = 2000 ;
    	} else if (fetchSize == 0){
    		fetchSize = 500 ;
    	}
    	
        config.setSourceQuerySQL(
        		SqlUtils.getFetchFirstXRowsSql(
        				table.getDbType(), sqlBuffer, fetchSize).toString());
        
	}
	
	@Override
	public void buildDestinationQuerySQL(){
		StringBuffer sqlBuffer = new StringBuffer() ;

		SyncTable table = config.getDestination() ;
		SyncColumn[] keys = table.getKeys();
		
        sqlBuffer.append("select ").append(keys[0].getSyncColumnsCode())
                 .append(" from ").append(table.getTableName());

        
        if (keys != null) {

        	sqlBuffer.append(" where ")
        	         .append(keys[0].getSyncColumnsCode()).append(">=? and ")
        	         .append(keys[0].getSyncColumnsCode()).append("<=?")  ;
 
        }
        //sql += " with ur " ;
        
    	int fetchSize = table.getConfig().getFetchSize() ;
    	if (fetchSize > 2000) {// 禁止大于2000
    		fetchSize = 2000 ;
    	} else if (fetchSize == 0){
    		fetchSize = 500 ;
    	}
    	
        config.setDestinationQuerySQL(
        		SqlUtils.getFetchFirstXRowsSql(
        				table.getDbType(), sqlBuffer, fetchSize).toString()) ;

        
	}

	
}
